package org.sintec.AndroidCarConnectivity;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;

import org.sintec.AndroidCarConnectivity.R;

import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.app.Activity;

public class activityDeviceList extends Activity 
{
	// Member fields
    private ArrayAdapter<String> mPairedDevicesArrayAdapter;
    private ArrayAdapter<String> mNewDevicesArrayAdapter;
    private BluetoothWrapper mBtWrapper;
    
    // Return Intent extra
    public static String EXTRA_DEVICE_ADDRESS = "device_address";
    
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        
        mBtWrapper = new BluetoothWrapper(this);
        
        // Setup the window
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        setContentView(R.layout.layout_device_list);
        
        // Set result CANCELED incase the user backs out
        setResult(Activity.RESULT_CANCELED);
        
        // Initialize the button to perform device discovery
        Button scanButton = (Button) findViewById(R.id.btnSearch);
        scanButton.setOnClickListener(new OnClickListener()
        {
            public void onClick(View v)
            {
            	mBtWrapper.doDiscovery();
                v.setVisibility(View.GONE);
            }
        });
        
        // Initialize array adapters. One for already paired devices and
        // one for newly discovered devices
        mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.layout_device_name);
        mNewDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.layout_device_name);
        
        // Find and set up the ListView for paired devices
        ListView pairedListView = (ListView) findViewById(R.id.paired_devices);
        pairedListView.setAdapter(mPairedDevicesArrayAdapter);
        pairedListView.setOnItemClickListener(mDeviceClickListener);
        
        // Find and set up the ListView for newly discovered devices
        ListView newDevicesListView = (ListView) findViewById(R.id.new_devices);
        newDevicesListView.setAdapter(mNewDevicesArrayAdapter);
        newDevicesListView.setOnItemClickListener(mDeviceClickListener);
        
        // Get a set of currently paired devices
        Set<BluetoothDevice> pairedDevices = mBtWrapper.getPairedDevices();

        // If there are paired devices, add each one to the ArrayAdapter
        if (pairedDevices.size() > 0) 
        {
            findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
            for (BluetoothDevice device : pairedDevices)
            {
                mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
            }
        } else 
        {
            String noDevices = getResources().getText(R.string.none_paired).toString();
            mPairedDevicesArrayAdapter.add(noDevices);
        }
    }
    
    public void updateListViews(ArrayAdapter<String> pairedDevices, ArrayAdapter<String> newDevices)
    {
    	
    }
    
    public void onDiscoveryStarted()
    {
        // Indicate scanning in the title
        setProgressBarIndeterminateVisibility(true);
        setTitle(R.string.scanning);
        
        // Turn on sub-title for new devices
        findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE);
    }
    
    public void onDiscoveryDeviceFound(BluetoothDevice device)
    {
    	mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
    }
    
    public void onDiscoveryFinished()
    {
    	setProgressBarIndeterminateVisibility(false);
    	setTitle(R.string.select_device);
        
    	if (mNewDevicesArrayAdapter.getCount() == 0) 
    	{
            String noDevices = getResources().getText(R.string.none_found).toString();
            mNewDevicesArrayAdapter.add(noDevices);
        }
    }
    
    // The on-click listener for all devices in the ListViews
    private OnItemClickListener mDeviceClickListener = new OnItemClickListener() 
    {
        public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) 
        {
        	mBtWrapper.doCancelDiscovery();

            // Get the device MAC address, which is the last 17 chars in the View
            String info = ((TextView) v).getText().toString();
            String address = info.substring(info.length() - 17);

            // Create the result Intent and include the MAC address
            Intent intent = new Intent();
            intent.putExtra(EXTRA_DEVICE_ADDRESS, address);

            // Set result and finish this Activity
            setResult(Activity.RESULT_OK, intent);
            finish();
            
            /*
            BluetoothSocket btSocket = null;
            
            try
            {
            	BluetoothDevice device = mBtWrapper.getBtAdapter().getRemoteDevice(address);
            	
            	try
            	{
            		UUID SPP_UUID = fromUUID16(0x1101); //UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
            		btSocket = device.createInsecureRfcommSocketToServiceRecord(SPP_UUID);
            	} catch (IOException e)
            	{
            		;
            	}
            	//btSocket = mBtWrapper.getBtAdapter().cre
            } catch (IllegalArgumentException e)
            {
            	
            }
            
            try 
            {
            	if (null != btSocket)
            	btSocket.connect();
            } catch(IOException e1)
            {
            	try
            	{
            		btSocket.close();
            	} catch (IOException e2)
            	{
            		;
            	}
            }
            
            OutputStream outStream = null;
            try
            {
            	if (null != outStream)
            		outStream = btSocket.getOutputStream();
            } catch (IOException e2)
            {
            	
            }
            
            try
            {
            	if (null != outStream)
            	{
	            	outStream.write(97);
	            	outStream.write(98);
	            	outStream.write(99);
            	}
            } catch (IOException e2)
            {
            	
            }
            */
        }
    };
    
    private UUID fromUUID16(int uuid16)
    {
    	String s = uuidStringFromUuid16(uuid16);
    	UUID uuid = UUID.fromString(s);
    	
    	return uuid;
    }
    
    private String uuidStringFromUuid16 (int uuid16)
    {
    	String UUID_BASE = "0000-1000-8000-00805F9B34FB";
    	int MASK_UUID16 = 0x0000FFFF;
    	
    	StringBuilder b = new StringBuilder();
    	String hex = Integer.toHexString(uuid16 & MASK_UUID16);
    	b.append("00000000".substring(hex.length()));
    	b.append(hex);
    	b.append('-');
    	b.append(UUID_BASE);
    	
    	return b.toString();
    }

}
